package com.adam.example.aggregation.bucket;

import com.adam.example.TransportClientHolder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.filters.Filters;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator;

import java.net.UnknownHostException;

public class FiltersAggregationExample {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient transportClient = TransportClientHolder.getInstance().getTransportClient();

        FiltersAggregationBuilder filtersAggregationBuilder = AggregationBuilders.filters("agg",
                new FiltersAggregator.KeyedFilter("java", QueryBuilders.termQuery("title", "java")),
                new FiltersAggregator.KeyedFilter("python", QueryBuilders.termQuery("title", "python")));
        //如果不用KeyedFilter直接传QueryBuilder参数，聚合结果中的key值为字符串0,1,...
        SearchResponse searchResponse = transportClient.prepareSearch("test_books")
                        .setSize(0).addAggregation(filtersAggregationBuilder).get();
        Filters filters = searchResponse.getAggregations().get("agg");
        for(Filters.Bucket bucket: filters.getBuckets()) {
            System.out.println(bucket.getKey() + ":" + bucket.getDocCount());
        }

        transportClient.close();
    }

}
